#include <REGX52.H>


//独立按键私有延时函数   @11.0592MHz   20ms
void MatrixKey_Delay()
{
	unsigned char i, j;

	i = 36;
	j = 217;
	do
	{
		while (--j);
	} while (--i);
}


/**
  * @brief  获取矩阵键盘键码
  * @param  无
  * @retval 按下按键的键码，范围：1~16，无按键按下时返回值为0
  */
unsigned char MatrixKey()
{
		unsigned char Keynum = 0;//返回0很很重要，否则会返回其他值
	
		P1 = 0xff;
		P1_7= 0;
		if(P1_3 == 0){ MatrixKey_Delay();while(P1_3 == 0); MatrixKey_Delay();Keynum = 1;}
		if(P1_2 == 0){ MatrixKey_Delay();while(P1_2 == 0); MatrixKey_Delay();Keynum = 2;}
		if(P1_1 == 0){ MatrixKey_Delay();while(P1_1 == 0); MatrixKey_Delay();Keynum = 3;}
		if(P1_0 == 0){ MatrixKey_Delay();while(P1_0 == 0); MatrixKey_Delay();Keynum = 4;}
		
		P1 = 0xff;
		P1_6 = 0;
		if(P1_3 == 0){ MatrixKey_Delay();while(P1_3 == 0); MatrixKey_Delay();Keynum = 5;}
		if(P1_2 == 0){ MatrixKey_Delay();while(P1_2 == 0); MatrixKey_Delay();Keynum = 6;}
		if(P1_1 == 0){ MatrixKey_Delay();while(P1_1 == 0); MatrixKey_Delay();Keynum = 7;}
		if(P1_0 == 0){ MatrixKey_Delay();while(P1_0 == 0); MatrixKey_Delay();Keynum = 8;}
		
		P1 = 0xff;
		P1_5 = 0;
		if(P1_3 == 0){ MatrixKey_Delay();while(P1_3 == 0); MatrixKey_Delay();Keynum = 9;}
		if(P1_2 == 0){ MatrixKey_Delay();while(P1_2 == 0); MatrixKey_Delay();Keynum = 10;}
		if(P1_1 == 0){ MatrixKey_Delay();while(P1_1 == 0); MatrixKey_Delay();Keynum = 11;}
		if(P1_0 == 0){ MatrixKey_Delay();while(P1_0 == 0); MatrixKey_Delay();Keynum = 12;}
		
		P1 = 0xff;
		P1_4 = 0;
		if(P1_3 == 0){ MatrixKey_Delay();while(P1_3 == 0); MatrixKey_Delay();Keynum = 13;}
		if(P1_2 == 0){ MatrixKey_Delay();while(P1_2 == 0); MatrixKey_Delay();Keynum = 14;}
		if(P1_1 == 0){ MatrixKey_Delay();while(P1_1 == 0); MatrixKey_Delay();Keynum = 15;}
		if(P1_0 == 0){ MatrixKey_Delay();while(P1_0 == 0); MatrixKey_Delay();Keynum = 16;}
		
		return Keynum;
}